/**
 * @FileName indexDBUtil
 * @Description
 * @Author renminghe
 * @Date 2018-12-28 15:58
 * @Version 1.0
 * @Copyright(c) gome inc Gome Co.,LTD
 **/

import Vue from "vue";

let _indexDBUtilIns = null;

class IndexDBUtil extends Vue {

    constructor () {
        super();

        this.db = null;
        this.store = null;
    }

    openDB (name="halo_editor", version=1) {

        const _this = this;

        if (!window.indexedDB) {
            this.$message.error("您的浏览器不支持indexDB，请安装最新版本谷歌浏览器");
            return;
        }

        return new Promise((resolve) => {
            const request = window.indexedDB.open(name, version);

            request.onerror = (e) => _this.$message.error(e.currentTarget.error.message);

            request.onsuccess =  (e) => {

                _this.db = e.target.result;

                resolve(_this.db);
            };

            request.onupgradeneeded = (e) => {

                const db = e.target.result;

                if(!db.objectStoreNames.contains('editor_config')) {
                    db.createObjectStore('editor_config',{autoIncrement: true});
                }

                _this.$message.warning('DB version changed to '+version);
            };
        });
    }

    insertData (data) {

        const transaction = this.db.transaction('editor_config','readwrite');
        const store = transaction.objectStore('editor_config');

        store.add(JSON.stringify(data), "editor_config");

    }

    updateData (data) {

        const transaction = this.db.transaction('editor_config','readwrite');
        const store = transaction.objectStore('editor_config');

        store.put(JSON.stringify(data), "editor_config");
    }

    async getAllData () {

        const transaction = this.db.transaction('editor_config','readwrite');
        const store = transaction.objectStore('editor_config');

        const res = store.get("editor_config");

        return new Promise(resolve => res.onsuccess = (e) => resolve(e.target.result));
    }

    clearAllData () {

        const transaction = this.db.transaction('editor_config','readwrite');
        const store = transaction.objectStore('editor_config');

        store.clear();
    }

    closeConnection () {

        this.db.close();
    }
}

IndexDBUtil.shared = () => {

    if (_indexDBUtilIns === null) {
        _indexDBUtilIns = new IndexDBUtil();
    }

    return _indexDBUtilIns;
};


export default IndexDBUtil.shared();